import time
from django.db import models
from django.core.validators import MinValueValidator


# 库存表
class FaKuyouGoodsStock(models.Model):
    STATUS_CHOICES = [
        ('0', '关仓'),
        ('1', '正常'),
    ]

    STOCK_WARNING_CHOICES = [
        ('0', '无预警'),
        ('1', '需预警'),
    ]

    id = models.AutoField(primary_key=True)
    admin_id = models.IntegerField(null=True, blank=True)
    goods_id = models.IntegerField(default=0, verbose_name='商品ID')
    goods_code = models.CharField(max_length=30, null=True, blank=True, verbose_name='商品编号')
    attribute_id = models.IntegerField(null=True, blank=True, verbose_name='属性组合ID')
    stores_id = models.IntegerField(default=0, verbose_name='仓库ID')
    stock = models.DecimalField(
        max_digits=15,
        decimal_places=4,
        default=0.0000,
        validators=[MinValueValidator(0)],
        verbose_name='库存数量'
    )
    status = models.CharField(
        max_length=1,
        choices=STATUS_CHOICES,
        default='1',
        verbose_name='库存状态'
    )
    period = models.DecimalField(
        max_digits=15,
        decimal_places=4,
        null=True,
        blank=True,
        default=0.0000,
        verbose_name='期初数量'
    )
    unit_cost = models.DecimalField(
        max_digits=15,
        decimal_places=4,
        default=0.0000,
        validators=[MinValueValidator(0)],
        verbose_name='单位成本'
    )
    price = models.DecimalField(
        max_digits=15,
        decimal_places=4,
        default=0.0000,
        validators=[MinValueValidator(0)],
        verbose_name='期初总价'
    )
    stock_warning = models.CharField(
        max_length=1,
        choices=STOCK_WARNING_CHOICES,
        default='0',
        verbose_name='库存预警'
    )
    min_stock = models.DecimalField(
        max_digits=15,
        decimal_places=4,
        default=0.0000,
        validators=[MinValueValidator(0)],
        verbose_name='最低库存'
    )
    max_stock = models.DecimalField(
        max_digits=15,
        decimal_places=4,
        default=0.0000,
        validators=[MinValueValidator(0)],
        verbose_name='最高库存'
    )
    address = models.CharField(max_length=255, null=True, blank=True, verbose_name='产地')
    registration = models.CharField(max_length=100, null=True, blank=True, verbose_name='注册证号')
    production = models.CharField(max_length=100, null=True, blank=True, verbose_name='生产许可证')
    cost_money = models.DecimalField(
        max_digits=15,
        decimal_places=4,
        default=0.0000,
        validators=[MinValueValidator(0)],
        verbose_name='总成本'
    )
    createtime = models.IntegerField(null=True, blank=True, verbose_name='创建时间')
    updatetime = models.IntegerField(null=True, blank=True, verbose_name='更新时间')
    deletetime = models.IntegerField(null=True, blank=True, verbose_name='删除时间')

    class Meta:
        db_table = 'fa_kuyou_goods_stock'
        verbose_name = '商品库存'
        verbose_name_plural = '商品库存'
        indexes = [
            models.Index(fields=['goods_id']),
            models.Index(fields=['goods_code']),
            models.Index(fields=['stores_id']),
            models.Index(fields=['status']),
        ]
        unique_together = (('goods_id', 'stores_id'),)  # 商品和仓库唯一组合

    def save(self, *args, **kwargs):
        # 自动计算期初总价
        if self.period and self.unit_cost:
            self.price = float(self.period) * float(self.unit_cost)

        # 自动计算总成本
        if self.stock and self.unit_cost:
            self.cost_money = float(self.stock) * float(self.unit_cost)

        # 自动检查库存预警状态
        if float(self.stock) < float(self.min_stock):
            self.stock_warning = '1'
        else:
            self.stock_warning = '0'

        super().save(*args, **kwargs)

    def __str__(self):
        return f"{self.goods_code or self.goods_id} - 仓库:{self.stores_id} - 库存:{self.stock}"


# 仓库表
class FaKuyouStores(models.Model):
    STATUS_CHOICES = [
        ('0', '关闭'),
        ('1', '正常')
    ]

    id = models.AutoField(primary_key=True, verbose_name='ID')
    admin_id = models.IntegerField(
        null=True,
        blank=True,
        verbose_name='管理员ID'
    )
    store_code = models.CharField(
        max_length=30,
        default='',
        verbose_name='仓库编号',
        help_text='建议使用字母数字组合'
    )
    name = models.CharField(
        max_length=255,
        default='',
        verbose_name='仓库名称'
    )
    status = models.CharField(
        max_length=1,
        choices=STATUS_CHOICES,
        default='1',
        verbose_name='仓库状态'
    )
    createtime = models.IntegerField(
        null=True,
        blank=True,
        verbose_name='创建时间'
    )
    updatetime = models.IntegerField(
        null=True,
        blank=True,
        verbose_name='更新时间'
    )

    class Meta:
        db_table = 'fa_kuyou_stores'
        verbose_name = '仓库信息'
        verbose_name_plural = '仓库管理'
        indexes = [
            models.Index(fields=['store_code']),
            models.Index(fields=['status']),
        ]
        ordering = ['store_code']

    def __str__(self):
        return f"{self.store_code}-{self.name}"

    def save(self, *args, **kwargs):
        # 自动维护时间戳
        now = int(time.time())
        self.createtime = now
        self.updatetime = now

        # 自动生成仓库编号（示例逻辑）
        if not self.store_code:
            last_store = FaKuyouStores.objects.order_by('-id').first()
            new_code = 'WH' + str(last_store.id + 1).zfill(4) if last_store else 'WH0001'
            self.store_code = new_code

        super().save(*args, **kwargs)


# 调拨单
class FaKuyouAllocation(models.Model):
    EXAMINE_STATUS_CHOICES = [
        ('0', '未审核'),
        ('1', '已审核')
    ]

    id = models.AutoField(primary_key=True, verbose_name='ID')
    admin_id = models.IntegerField(
        null=True,
        blank=True,
        verbose_name='管理员ID'
    )

    # 单据信息
    purchase_code = models.CharField(
        max_length=50,
        default='',
        verbose_name='调拨单号'
    )
    purchase_time = models.IntegerField(
        null=True,
        blank=True,
        verbose_name='单据日期'
    )

    # 人员信息
    preparation_id = models.IntegerField(
        null=True,
        blank=True,
        verbose_name='制单人ID'
    )
    examine_id = models.IntegerField(
        null=True,
        blank=True,
        verbose_name='审核人ID'
    )
    operation_id = models.IntegerField(
        null=True,
        blank=True,
        verbose_name='操作人ID'
    )

    # 审核信息
    examine_status = models.CharField(
        max_length=1,
        choices=EXAMINE_STATUS_CHOICES,
        default='0',
        verbose_name='审核状态'
    )
    examine_time = models.IntegerField(
        null=True,
        blank=True,
        verbose_name='审核时间'
    )

    # 其他信息
    remarks = models.CharField(
        max_length=255,
        null=True,
        blank=True,
        verbose_name='备注'
    )
    print_num = models.IntegerField(
        default=0,
        verbose_name='打印次数'
    )
    createtime = models.IntegerField(
        null=True,
        blank=True,
        verbose_name='创建时间'
    )
    updatetime = models.IntegerField(
        null=True,
        blank=True,
        verbose_name='更新时间'
    )

    class Meta:
        db_table = 'fa_kuyou_allocation'
        verbose_name = '调拨单'
        verbose_name_plural = '调拨单管理'
        indexes = [
            models.Index(fields=['purchase_code']),
            models.Index(fields=['examine_status']),
        ]
        ordering = ['-purchase_time']

    def __str__(self):
        return f"调拨单-{self.purchase_code or '新单据'}"

    def save(self, *args, **kwargs):
        # 自动维护时间戳
        now = int(time.time())
        self.createtime = now
        self.updatetime = now

        # 审核时自动记录审核时间
        if self.examine_status == '1' and not self.examine_time:
            self.examine_time = now

        super().save(*args, **kwargs)


# 调拨详情单
class FaKuyouAllocationInfo(models.Model):
    id = models.AutoField(primary_key=True, verbose_name='ID')
    admin_id = models.IntegerField(
        null=True,
        blank=True,
        verbose_name='管理员ID'
    )

    # 调拨关联信息
    allocation_id = models.CharField(
        max_length=50,
        default='',
        verbose_name='调拨单号'
    )

    # 商品信息
    goods_id = models.IntegerField(
        null=True,
        blank=True,
        verbose_name='商品ID'
    )
    goods_attr = models.IntegerField(
        null=True,
        blank=True,
        verbose_name='商品属性'
    )
    goods_unit = models.IntegerField(
        null=True,
        blank=True,
        verbose_name='商品单位ID'
    )

    # 仓库信息
    stores_out = models.IntegerField(
        null=True,
        blank=True,
        verbose_name='调出仓库ID'
    )
    stores_enter = models.IntegerField(
        null=True,
        blank=True,
        verbose_name='调入仓库ID'
    )

    # 调拨信息
    number = models.IntegerField(
        null=True,
        blank=True,
        validators=[MinValueValidator(1)],
        verbose_name='调拨数量'
    )
    goods_batch_id = models.IntegerField(
        null=True,
        blank=True,
        verbose_name='批次ID',
        default=0
    )
    goods_batch_name = models.CharField(
        max_length=255,
        null=True,
        blank=True,
        verbose_name='批次名称',
        default=""
    )
    goods_serial_id = models.TextField(
        null=True,
        blank=True,
        verbose_name='序列号',
        default=None
    )

    # 其他信息
    remarks = models.CharField(
        max_length=255,
        null=True,
        blank=True,
        verbose_name='分录备注',
        default=""
    )
    allow_stock = models.DecimalField(
        max_digits=15,
        decimal_places=4,
        default=0.0000,
        verbose_name='可用库存'
    )
    goods_note = models.CharField(
        max_length=255,
        null=True,
        blank=True,
        verbose_name='商品备注'
    )

    class Meta:
        db_table = 'fa_kuyou_allocation_info'
        verbose_name = '调拨单详情'
        verbose_name_plural = '调拨单详情管理'
        indexes = [
            models.Index(fields=['allocation_id']),
            models.Index(fields=['goods_id']),
            models.Index(fields=['stores_out']),
            models.Index(fields=['stores_enter']),
        ]
        ordering = ['-id']

    def __str__(self):
        return f"调拨明细-{self.allocation_id}-{self.goods_id or '无商品'}"


# 成本调整单
class FaKuyouAdjustment(models.Model):
    BUSINESS_TYPE_CHOICES = [
        ('1', '成本调整')
    ]

    id = models.AutoField(primary_key=True, verbose_name='ID')
    admin_id = models.IntegerField(
        null=True,
        blank=True,
        verbose_name='管理员ID'
    )

    # 单据信息
    purchase_code = models.CharField(
        max_length=50,
        null=True,
        blank=True,
        verbose_name='调整单号',
        unique=True
    )
    purchase_time = models.IntegerField(
        null=True,
        blank=True,
        verbose_name='单据日期'
    )
    business_type = models.CharField(
        max_length=1,
        choices=BUSINESS_TYPE_CHOICES,
        null=True,
        blank=True,
        verbose_name='业务类型'
    )

    # 金额信息
    money = models.DecimalField(
        max_digits=15,
        decimal_places=4,
        null=True,
        blank=True,
        validators=[MinValueValidator(0.0001)],
        verbose_name='调整金额'
    )

    # 人员信息
    preparation_id = models.IntegerField(
        null=True,
        blank=True,
        verbose_name='制单人ID'
    )

    # 其他信息
    remark = models.CharField(
        max_length=255,
        null=True,
        blank=True,
        verbose_name='备注'
    )
    print_num = models.IntegerField(
        null=True,
        blank=True,
        default=0,
        verbose_name='打印次数'
    )
    createtime = models.IntegerField(
        null=True,
        blank=True,
        verbose_name='创建时间'
    )
    updatetime = models.IntegerField(
        null=True,
        blank=True,
        verbose_name='更新时间'
    )

    class Meta:
        db_table = 'fa_kuyou_adjustment'
        verbose_name = '成本调整单'
        verbose_name_plural = '成本调整单管理'
        indexes = [
            models.Index(fields=['purchase_code']),
            models.Index(fields=['purchase_time']),
        ]
        ordering = ['-purchase_time']

    def __str__(self):
        return f"成本调整单-{self.purchase_code or '新单据'}"

    def save(self, *args, **kwargs):
        # 自动维护时间戳
        now = int(time.time())
        self.createtime = now
        self.updatetime = now

        # 自动生成单号（示例规则：CJ+年月日+4位随机数）
        if not self.purchase_code:
            from datetime import datetime
            import random
            date_str = datetime.now().strftime('%Y%m%d')
            random_str = str(random.randint(1000, 9999))
            self.purchase_code = f"CJ{date_str}{random_str}"

        super().save(*args, **kwargs)


# 成本调整单详情
class FaKuyouAdjustmentInfo(models.Model):
    id = models.AutoField(primary_key=True, verbose_name='ID')
    admin_id = models.IntegerField(
        null=True,
        blank=True,
        verbose_name='管理员ID'
    )

    # 单据关联信息
    purchase_code = models.CharField(
        max_length=50,
        null=True,
        blank=True,
        verbose_name='调整单号'
    )
    purchase_time = models.IntegerField(
        null=True,
        blank=True,
        verbose_name='单据日期'
    )

    # 商品信息
    goods_id = models.IntegerField(
        null=True,
        blank=True,
        verbose_name='商品ID'
    )
    goods_unit = models.IntegerField(
        default=0,
        verbose_name='单位ID'
    )

    # 金额信息
    money = models.DecimalField(
        max_digits=15,
        decimal_places=4,
        null=True,
        blank=True,
        validators=[MinValueValidator(0.0001)],
        verbose_name='调整金额'
    )

    # 仓库信息
    stores_id = models.IntegerField(
        null=True,
        blank=True,
        verbose_name='仓库ID'
    )

    # 其他信息
    remark = models.CharField(
        max_length=255,
        null=True,
        blank=True,
        verbose_name='备注'
    )
    createtime = models.IntegerField(
        null=True,
        blank=True,
        verbose_name='创建时间'
    )
    updatetime = models.IntegerField(
        null=True,
        blank=True,
        verbose_name='更新时间'
    )

    class Meta:
        db_table = 'fa_kuyou_adjustment_info'
        verbose_name = '成本调整单详情'
        verbose_name_plural = '成本调整单详情管理'
        indexes = [
            models.Index(fields=['purchase_code']),
            models.Index(fields=['goods_id']),
            models.Index(fields=['stores_id']),
        ]
        ordering = ['-purchase_time']

    def __str__(self):
        return f"调整明细-{self.purchase_code or '新单据'}"

    def save(self, *args, **kwargs):
        # 自动维护时间戳
        now = int(time.time())
        self.createtime = now
        self.updatetime = now

        super().save(*args, **kwargs)


# 盘点
class FaKuyouInventory(models.Model):
    STORE_TYPE_CHOICES = [
        ('1', '全部仓库'),
        ('2', '单仓')
    ]

    id = models.AutoField(primary_key=True, verbose_name='ID')
    admin_id = models.IntegerField(
        null=True,
        blank=True,
        verbose_name='管理员ID'
    )

    # 盘点单据信息
    purchase_code = models.CharField(
        max_length=50,
        null=True,
        blank=True,
        unique=True,
        verbose_name='盘点单号'
    )
    purchase_time = models.IntegerField(
        null=True,
        blank=True,
        verbose_name='盘点时间'
    )

    # 仓库类型
    store_type = models.CharField(
        max_length=1,
        choices=STORE_TYPE_CHOICES,
        default='1',
        verbose_name='盘点范围'
    )

    # 盘点结果
    result = models.CharField(
        max_length=255,
        null=True,
        blank=True,
        verbose_name='盘点结果'
    )

    # 时间信息
    createtime = models.IntegerField(
        null=True,
        blank=True,
        verbose_name='创建时间'
    )
    updatetime = models.IntegerField(
        null=True,
        blank=True,
        verbose_name='更新时间'
    )

    class Meta:
        db_table = 'fa_kuyou_inventory'
        verbose_name = '盘点单'
        verbose_name_plural = '盘点管理'
        indexes = [
            models.Index(fields=['purchase_code']),
            models.Index(fields=['purchase_time']),
        ]
        ordering = ['-purchase_time']

    def __str__(self):
        return f"盘点单-{self.purchase_code or '新单据'}"

    def save(self, *args, **kwargs):
        # 自动维护时间戳
        now = int(time.time())
        self.createtime = now
        self.updatetime = now

        # 自动生成盘点单号（示例规则：PD+年月日+4位随机数）
        if not self.purchase_code:
            from datetime import datetime
            import random
            date_str = datetime.now().strftime('%Y%m%d')
            random_str = str(random.randint(1000, 9999))
            self.purchase_code = f"PD{date_str}{random_str}"

        super().save(*args, **kwargs)


# 盘点详情
class FaKuyouInventoryInfo(models.Model):
    id = models.AutoField(primary_key=True, verbose_name='ID')
    admin_id = models.IntegerField(
        null=True,
        blank=True,
        verbose_name='管理员ID'
    )

    # 单据关联信息
    purchase_code = models.CharField(
        max_length=50,
        null=True,
        blank=True,
        verbose_name='盘点单号'
    )
    purchase_time = models.IntegerField(
        null=True,
        blank=True,
        verbose_name='盘点时间'
    )

    # 商品信息
    goods_type = models.IntegerField(
        null=True,
        blank=True,
        verbose_name='商品类别'
    )
    goods_id = models.IntegerField(
        null=True,
        blank=True,
        verbose_name='商品ID'
    )
    goods_attr = models.IntegerField(
        null=True,
        blank=True,
        verbose_name='商品属性'
    )

    # 仓库信息
    stores_id = models.IntegerField(
        null=True,
        blank=True,
        verbose_name='仓库ID'
    )

    # 库存信息
    stock = models.DecimalField(
        max_digits=15,
        decimal_places=4,
        null=True,
        blank=True,
        validators=[MinValueValidator(0)],
        verbose_name='系统库存'
    )
    invertory_stock = models.DecimalField(
        max_digits=15,
        decimal_places=4,
        null=True,
        blank=True,
        validators=[MinValueValidator(0)],
        verbose_name='盘点库存'
    )
    profit = models.DecimalField(
        max_digits=15,
        decimal_places=4,
        null=True,
        blank=True,
        verbose_name='盘盈盘亏'
    )

    # 时间信息
    createtime = models.IntegerField(
        null=True,
        blank=True,
        verbose_name='创建时间'
    )
    updatetime = models.IntegerField(
        null=True,
        blank=True,
        verbose_name='更新时间'
    )

    class Meta:
        db_table = 'fa_kuyou_inventory_info'
        verbose_name = '盘点明细'
        verbose_name_plural = '盘点明细管理'
        indexes = [
            models.Index(fields=['purchase_code']),
            models.Index(fields=['goods_id']),
            models.Index(fields=['stores_id']),
        ]
        ordering = ['-purchase_time']

    def __str__(self):
        return f"盘点明细-{self.purchase_code or '新单据'}"

    def save(self, *args, **kwargs):
        # 自动维护时间戳
        now = int(time.time())
        self.createtime = now
        self.updatetime = now

        # 自动计算盘盈盘亏
        if self.stock is not None and self.invertory_stock is not None:
            self.profit = self.invertory_stock - self.stock

        super().save(*args, **kwargs)


# 序列号盘点
class FaKuyouInventorySerial(models.Model):
    STORE_TYPE_CHOICES = [
        ('1', '全部仓库'),
        ('2', '单仓')
    ]

    id = models.AutoField(primary_key=True, verbose_name='ID')
    admin_id = models.IntegerField(
        null=True,
        blank=True,
        verbose_name='管理员ID'
    )

    # 单据信息
    purchase_code = models.CharField(
        max_length=50,
        null=True,
        blank=True,
        unique=True,
        verbose_name='盘点单号'
    )
    purchase_time = models.IntegerField(
        null=True,
        blank=True,
        verbose_name='盘点时间'
    )

    # 盘点范围
    store_type = models.CharField(
        max_length=1,
        choices=STORE_TYPE_CHOICES,
        default='1',
        verbose_name='盘点范围'
    )

    # 盘点结果
    result = models.CharField(
        max_length=255,
        null=True,
        blank=True,
        verbose_name='盘点结果'
    )

    # 时间信息
    createtime = models.IntegerField(
        null=True,
        blank=True,
        verbose_name='创建时间'
    )
    updatetime = models.IntegerField(
        null=True,
        blank=True,
        verbose_name='更新时间'
    )

    class Meta:
        db_table = 'fa_kuyou_inventory_serial'
        verbose_name = '序列号盘点单'
        verbose_name_plural = '序列号盘点管理'
        indexes = [
            models.Index(fields=['purchase_code']),
            models.Index(fields=['purchase_time']),
        ]
        ordering = ['-purchase_time']

    def __str__(self):
        return f"序列号盘点-{self.purchase_code or '新单据'}"

    def save(self, *args, **kwargs):
        # 自动维护时间戳
        now = int(time.time())
        self.createtime = now
        self.updatetime = now

        # 自动生成盘点单号（示例规则：SPD+年月日+4位随机数）
        if not self.purchase_code:
            from datetime import datetime
            import random
            date_str = datetime.now().strftime('%Y%m%d')
            random_str = str(random.randint(1000, 9999))
            self.purchase_code = f"SPD{date_str}{random_str}"

        super().save(*args, **kwargs)


# 序列号盘点详情
class FaKuyouInventorySerialInfo(models.Model):
    id = models.AutoField(primary_key=True, verbose_name='ID')
    admin_id = models.IntegerField(
        null=True,
        blank=True,
        verbose_name='管理员ID'
    )

    # 单据关联信息
    purchase_code = models.CharField(
        max_length=50,
        null=True,
        blank=True,
        verbose_name='盘点单号'
    )
    purchase_time = models.IntegerField(
        null=True,
        blank=True,
        verbose_name='盘点时间'
    )

    # 商品信息
    goods_type = models.IntegerField(
        null=True,
        blank=True,
        verbose_name='商品类别'
    )
    goods_id = models.IntegerField(
        null=True,
        blank=True,
        verbose_name='商品ID'
    )
    goods_attr = models.IntegerField(
        null=True,
        blank=True,
        verbose_name='商品属性'
    )

    # 仓库信息
    stores_id = models.IntegerField(
        null=True,
        blank=True,
        verbose_name='仓库ID'
    )

    # 库存信息
    stock = models.DecimalField(
        max_digits=15,
        decimal_places=4,
        null=True,
        blank=True,
        validators=[MinValueValidator(0)],
        verbose_name='系统库存'
    )
    invertory_stock = models.DecimalField(
        max_digits=15,
        decimal_places=4,
        null=True,
        blank=True,
        validators=[MinValueValidator(0)],
        verbose_name='盘点库存'
    )
    profit = models.DecimalField(
        max_digits=15,
        decimal_places=4,
        null=True,
        blank=True,
        verbose_name='盘盈盘亏'
    )

    # 序列号信息
    period_period = models.TextField(
        null=True,
        blank=True,
        verbose_name='序列号清单'
    )

    # 盘点结果
    matching = models.IntegerField(
        null=True,
        blank=True,
        verbose_name='匹配数量'
    )
    inventory = models.IntegerField(
        null=True,
        blank=True,
        verbose_name='盘盈数量'
    )
    loss = models.IntegerField(
        null=True,
        blank=True,
        verbose_name='盘亏数量'
    )

    # 时间信息
    createtime = models.IntegerField(
        null=True,
        blank=True,
        verbose_name='创建时间'
    )
    updatetime = models.IntegerField(
        null=True,
        blank=True,
        verbose_name='更新时间'
    )

    class Meta:
        db_table = 'fa_kuyou_inventory_serial_info'
        verbose_name = '序列号盘点明细'
        verbose_name_plural = '序列号盘点明细管理'
        indexes = [
            models.Index(fields=['purchase_code']),
            models.Index(fields=['goods_id']),
            models.Index(fields=['stores_id']),
        ]
        ordering = ['-purchase_time']

    def __str__(self):
        return f"序列号盘点-{self.purchase_code or '新单据'}"

    def save(self, *args, **kwargs):
        # 自动维护时间戳
        now = int(time.time())
        self.createtime = now
        self.updatetime = now

        # 自动计算盘盈盘亏
        if self.stock is not None and self.invertory_stock is not None:
            self.profit = self.invertory_stock - self.stock

        # 自动计算序列号盘点结果
        if self.period_period:
            serials = self.period_period.split(',')
            total_count = len(serials)

            # 这里需要根据业务逻辑计算匹配、盘盈、盘亏数量
            # 示例逻辑（需根据实际业务调整）：
            self.matching = total_count - (self.inventory or 0) - (self.loss or 0)

        super().save(*args, **kwargs)


# 其他入库单
class FaKuyouWarehousing(models.Model):
    BUSINESS_TYPE_CHOICES = [
        ('1', '盘盈入库'),
        ('2', '其他入库')
    ]

    EXAMINE_STATUS_CHOICES = [
        ('0', '未审核'),
        ('1', '已审核')
    ]

    ORDER_TYPE_CHOICES = [
        ('1', '盘点单'),
        ('2', '序列号盘点单')
    ]

    id = models.AutoField(primary_key=True, verbose_name='ID')
    admin_id = models.IntegerField(
        null=True,
        blank=True,
        verbose_name='管理员ID'
    )

    # 单据信息
    purchase_code = models.CharField(
        max_length=50,
        null=True,
        blank=True,
        unique=True,
        verbose_name='入库单号'
    )
    purchase_time = models.IntegerField(
        null=True,
        blank=True,
        verbose_name='单据时间'
    )
    business_type = models.CharField(
        max_length=1,
        choices=BUSINESS_TYPE_CHOICES,
        verbose_name='业务类型'
    )

    # 入库信息
    number = models.DecimalField(
        max_digits=15,
        decimal_places=4,
        validators=[MinValueValidator(0.0001)],
        verbose_name='入库数量'
    )
    price = models.DecimalField(
        max_digits=15,
        decimal_places=4,
        validators=[MinValueValidator(0)],
        verbose_name='入库金额'
    )

    # 关联信息
    suppliers_id = models.IntegerField(
        null=True,
        blank=True,
        verbose_name='供应商ID'
    )
    order_id = models.IntegerField(
        null=True,
        blank=True,
        verbose_name='关联单号ID'
    )
    order_type = models.CharField(
        max_length=1,
        choices=ORDER_TYPE_CHOICES,
        null=True,
        blank=True,
        verbose_name='单据类型'
    )

    # 人员信息
    preparation_id = models.IntegerField(
        null=True,
        blank=True,
        verbose_name='制单人ID'
    )
    examine_id = models.IntegerField(
        null=True,
        blank=True,
        verbose_name='审核人ID'
    )
    operation_id = models.IntegerField(
        null=True,
        blank=True,
        verbose_name='操作人ID'
    )

    # 审核信息
    examine_status = models.CharField(
        max_length=1,
        choices=EXAMINE_STATUS_CHOICES,
        default='0',
        verbose_name='审核状态'
    )
    examine_time = models.IntegerField(
        null=True,
        blank=True,
        verbose_name='审核时间'
    )

    # 其他信息
    remarks = models.CharField(
        max_length=255,
        null=True,
        blank=True,
        verbose_name='备注'
    )
    print_num = models.IntegerField(
        null=True,
        blank=True,
        default=0,
        verbose_name='打印次数'
    )
    createtime = models.IntegerField(
        null=True,
        blank=True,
        verbose_name='创建时间'
    )
    updatetime = models.IntegerField(
        null=True,
        blank=True,
        verbose_name='更新时间'
    )

    class Meta:
        db_table = 'fa_kuyou_warehousing'
        verbose_name = '其他入库单'
        verbose_name_plural = '其他入库单管理'
        indexes = [
            models.Index(fields=['purchase_code']),
            models.Index(fields=['purchase_time']),
            models.Index(fields=['examine_status']),
        ]
        ordering = ['-purchase_time']

    def __str__(self):
        return f"入库单-{self.purchase_code or '新单据'}"

    def save(self, *args, **kwargs):
        # 自动维护时间戳
        now = int(time.time())
        self.createtime = now
        self.updatetime = now

        # 审核时自动记录审核时间
        if self.examine_status == '1' and not self.examine_time:
            self.examine_time = now

        # 自动生成入库单号（示例规则：RK+年月日+4位随机数）
        if not self.purchase_code:
            from datetime import datetime
            import random
            date_str = datetime.now().strftime('%Y%m%d')
            random_str = str(random.randint(1000, 9999))
            self.purchase_code = f"RK{date_str}{random_str}"

        super().save(*args, **kwargs)


# 其他入库单详情
class FaKuyouWarehousingInfo(models.Model):
    id = models.AutoField(primary_key=True, verbose_name='ID')
    admin_id = models.IntegerField(
        null=True,
        blank=True,
        verbose_name='管理员ID'
    )

    # 单据关联信息
    purchase_code = models.CharField(
        max_length=50,
        null=True,
        blank=True,
        verbose_name='入库单号'
    )
    purchase_time = models.IntegerField(
        null=True,
        blank=True,
        verbose_name='入库时间'
    )

    # 商品信息
    goods_id = models.IntegerField(
        null=True,
        blank=True,
        verbose_name='商品ID'
    )
    goods_attr = models.IntegerField(
        null=True,
        blank=True,
        verbose_name='商品属性'
    )
    goods_unit = models.IntegerField(
        null=True,
        blank=True,
        verbose_name='商品单位'
    )

    # 仓库信息
    stores_id = models.IntegerField(
        null=True,
        blank=True,
        verbose_name='仓库ID'
    )

    # 库存信息
    stock = models.DecimalField(
        max_digits=15,
        decimal_places=4,
        null=True,
        blank=True,
        validators=[MinValueValidator(0)],
        verbose_name='可用库存'
    )
    number = models.DecimalField(
        max_digits=15,
        decimal_places=4,
        null=True,
        blank=True,
        validators=[MinValueValidator(0.0001)],
        verbose_name='入库数量'
    )
    basic_nmber = models.DecimalField(
        max_digits=15,
        decimal_places=4,
        null=True,
        blank=True,
        validators=[MinValueValidator(0.0001)],
        verbose_name='基础数量'
    )

    # 序列号信息
    period = models.TextField(
        null=True,
        blank=True,
        verbose_name='序列号清单'
    )

    # 价格信息
    unit_price = models.DecimalField(
        max_digits=15,
        decimal_places=4,
        null=True,
        blank=True,
        validators=[MinValueValidator(0)],
        verbose_name='入库单价'
    )
    price = models.DecimalField(
        max_digits=15,
        decimal_places=4,
        null=True,
        blank=True,
        verbose_name='入库金额'
    )

    # 批次信息
    batch = models.CharField(
        max_length=255,
        null=True,
        blank=True,
        verbose_name='批次号'
    )
    batch_id = models.IntegerField(
        null=True,
        blank=True,
        verbose_name='批次ID'
    )

    # 保质期信息
    manufacture = models.IntegerField(
        null=True,
        blank=True,
        verbose_name='生产日期'
    )
    guarantee = models.IntegerField(
        null=True,
        blank=True,
        verbose_name='保质期(天)'
    )
    validity = models.IntegerField(
        null=True,
        blank=True,
        verbose_name='有效期至'
    )

    # 其他信息
    remark = models.CharField(
        max_length=255,
        null=True,
        blank=True,
        verbose_name='备注'
    )
    createtime = models.IntegerField(
        null=True,
        blank=True,
        verbose_name='创建时间'
    )
    updatetime = models.IntegerField(
        null=True,
        blank=True,
        verbose_name='更新时间'
    )

    class Meta:
        db_table = 'fa_kuyou_warehousing_info'
        verbose_name = '入库单明细'
        verbose_name_plural = '入库单明细管理'
        indexes = [
            models.Index(fields=['purchase_code']),
            models.Index(fields=['goods_id']),
            models.Index(fields=['stores_id']),
            models.Index(fields=['batch']),
        ]
        ordering = ['-purchase_time']

    def __str__(self):
        return f"入库明细-{self.purchase_code or '新单据'}"

    def save(self, *args, **kwargs):
        # 自动维护时间戳
        now = int(time.time())
        self.createtime = now
        self.updatetime = now

        # 自动计算入库金额
        if self.unit_price is not None and self.number is not None:
            self.price = self.unit_price * self.number
        super().save(*args, **kwargs)


# 其他出库单
class FaKuyouWarehouse(models.Model):
    BUSINESS_TYPE_CHOICES = [
        ('1', '盘亏'),
        ('2', '其他出库'),
    ]

    EXAMINE_STATUS_CHOICES = [
        ('0', '未审核'),
        ('1', '已审核'),
    ]

    ORDER_TYPE_CHOICES = [
        ('1', '盘点'),
        ('2', '序列号盘点'),
    ]

    id = models.AutoField(primary_key=True)
    admin_id = models.IntegerField(null=True, blank=True)
    purchase_code = models.CharField(max_length=50, null=True, blank=True, verbose_name='单据编号')
    purchase_time = models.IntegerField(null=True, blank=True, verbose_name='单据时间')
    business_type = models.CharField(
        max_length=1,
        choices=BUSINESS_TYPE_CHOICES,
        null=True,
        blank=True,
        verbose_name='业务类别'
    )
    number = models.DecimalField(
        max_digits=15,
        decimal_places=4,
        null=True,
        blank=True,
        verbose_name='数量'
    )
    price = models.DecimalField(
        max_digits=15,
        decimal_places=4,
        null=True,
        blank=True,
        verbose_name='金额'
    )
    customers_id = models.IntegerField(null=True, blank=True, verbose_name='客户ID')
    preparation_id = models.IntegerField(null=True, blank=True, verbose_name='制单人ID')
    examine_id = models.IntegerField(null=True, blank=True, verbose_name='审核人ID')
    operation_id = models.IntegerField(null=True, blank=True, verbose_name='最后操作人ID')
    examine_time = models.IntegerField(null=True, blank=True, verbose_name='审核时间')
    examine_status = models.CharField(
        max_length=1,
        choices=EXAMINE_STATUS_CHOICES,
        default='0',
        verbose_name='审核状态'
    )
    remarks = models.CharField(max_length=255, null=True, blank=True, verbose_name='备注')
    print_num = models.IntegerField(null=True, blank=True, verbose_name='打印次数')
    order_id = models.IntegerField(null=True, blank=True, verbose_name='盘点单ID')
    order_type = models.CharField(
        max_length=1,
        choices=ORDER_TYPE_CHOICES,
        null=True,
        blank=True,
        verbose_name='单据类型'
    )
    createtime = models.IntegerField(null=True, blank=True, verbose_name='创建时间', default=int(time.time()))
    updatetime = models.IntegerField(null=True, blank=True, verbose_name='更新时间', default=int(time.time()))

    class Meta:
        db_table = 'fa_kuyou_warehouse'
        verbose_name = '其他出库单'
        verbose_name_plural = '其他出库单'
        indexes = [
            models.Index(fields=['purchase_code']),
            models.Index(fields=['customers_id']),
            models.Index(fields=['examine_status']),
        ]

    def __str__(self):
        return f"{self.purchase_code or '无编号'} - {self.get_business_type_display()}"


# 其他出库详情单
class FaKuyouWarehouseInfo(models.Model):
    id = models.AutoField(primary_key=True)
    admin_id = models.IntegerField(null=True, blank=True)
    purchase_code = models.CharField(max_length=50, null=True, blank=True, verbose_name='盘点编号')
    purchase_time = models.IntegerField(null=True, blank=True, verbose_name='盘点时间')
    goods_id = models.IntegerField(null=True, blank=True, verbose_name='商品ID')
    goods_attr = models.IntegerField(null=True, blank=True, verbose_name='商品属性ID')
    goods_unit = models.IntegerField(null=True, blank=True, verbose_name='商品单位ID')
    stores_id = models.IntegerField(null=True, blank=True, verbose_name='仓库ID')
    stock = models.DecimalField(
        max_digits=15,
        decimal_places=4,
        null=True,
        blank=True,
        verbose_name='可用库存'
    )
    number = models.DecimalField(
        max_digits=15,
        decimal_places=4,
        null=True,
        blank=True,
        verbose_name='数量'
    )
    basic_nmber = models.DecimalField(
        max_digits=15,
        decimal_places=4,
        null=True,
        blank=True,
        verbose_name='基础数量'
    )
    period = models.TextField(null=True, blank=True, verbose_name='序列号')
    unit_price = models.DecimalField(
        max_digits=15,
        decimal_places=4,
        null=True,
        blank=True,
        verbose_name='出库单价'
    )
    price = models.DecimalField(
        max_digits=15,
        decimal_places=4,
        null=True,
        blank=True,
        verbose_name='出库金额'
    )
    remark = models.CharField(max_length=255, null=True, blank=True, verbose_name='备注')
    batch = models.CharField(max_length=255, null=True, blank=True, verbose_name='批次')
    batch_id = models.IntegerField(null=True, blank=True, verbose_name='批次ID')
    manufacture = models.IntegerField(null=True, blank=True, verbose_name='生产日期')
    guarantee = models.IntegerField(null=True, blank=True, verbose_name='保质期(天)')
    validity = models.IntegerField(null=True, blank=True, verbose_name='有效期至')
    createtime = models.IntegerField(null=True, blank=True, verbose_name='创建时间', default=int(time.time()))
    updatetime = models.IntegerField(null=True, blank=True, verbose_name='更新时间', default=int(time.time()))

    class Meta:
        db_table = 'fa_kuyou_warehouse_info'
        verbose_name = '其他出库单详情'
        verbose_name_plural = '其他出库单详情'
        indexes = [
            models.Index(fields=['purchase_code']),
            models.Index(fields=['goods_id']),
            models.Index(fields=['stores_id']),
            models.Index(fields=['batch']),
        ]

    def __str__(self):
        return f"{self.purchase_code or '无编号'} - 商品ID:{self.goods_id}"

    def save(self, *args, **kwargs):
        """Auto calculate price if not set"""
        if self.unit_price is not None and self.number is not None and self.price is None:
            self.price = float(self.unit_price) * float(self.number)
        super().save(*args, **kwargs)


# 组装单
class FaKuyouAssemble(models.Model):
    BUSINESS_TYPE_CHOICES = [
        ('1', '组装单'),
    ]

    EXAMINE_STATUS_CHOICES = [
        ('0', '未审核'),
        ('1', '已审核'),
    ]

    id = models.AutoField(primary_key=True)
    admin_id = models.IntegerField(null=True, blank=True)
    purchase_code = models.CharField(
        max_length=50,
        null=True,
        blank=True,
        verbose_name='单据编号'
    )
    purchase_time = models.IntegerField(
        null=True,
        blank=True,
        verbose_name='单据日期'
    )
    business_type = models.CharField(
        max_length=1,
        choices=BUSINESS_TYPE_CHOICES,
        null=True,
        blank=True,
        verbose_name='业务类型'
    )
    money = models.DecimalField(
        max_digits=15,
        decimal_places=4,
        null=True,
        blank=True,
        verbose_name='费用'
    )
    remark = models.CharField(
        max_length=255,
        null=True,
        blank=True,
        verbose_name='备注'
    )
    preparation_id = models.IntegerField(
        null=True,
        blank=True,
        verbose_name='制单人ID'
    )
    operation_id = models.IntegerField(
        null=True,
        blank=True,
        verbose_name='最后操作人ID'
    )
    examine_id = models.IntegerField(
        null=True,
        blank=True,
        verbose_name='审核人ID'
    )
    examine_status = models.CharField(
        max_length=1,
        choices=EXAMINE_STATUS_CHOICES,
        default='0',
        null=True,
        verbose_name='审核状态'
    )
    examine_time = models.IntegerField(
        null=True,
        blank=True,
        verbose_name='审核时间'
    )
    print_num = models.IntegerField(
        null=True,
        blank=True,
        verbose_name='打印次数'
    )
    createtime = models.IntegerField(
        null=True,
        blank=True,
        verbose_name='创建时间',
        default=int(time.time())
    )
    updatetime = models.IntegerField(
        null=True,
        blank=True,
        verbose_name='更新时间',
        default=int(time.time())
    )

    class Meta:
        db_table = 'fa_kuyou_assemble'
        verbose_name = '组装单'
        verbose_name_plural = '组装单'
        indexes = [
            models.Index(fields=['purchase_code']),
            models.Index(fields=['examine_status']),
            models.Index(fields=['purchase_time']),
        ]

    def __str__(self):
        return f"组装单 {self.purchase_code or self.id}"


# 组装详情单
class FaKuyouAssembleInfo(models.Model):
    """组装单详情表"""
    BUSINESS_TYPE_CHOICES = [
        ('1', '组装单'),
    ]
    TYPE_CHOICES = [
        ('1', '组合件'),
        ('2', '子件'),
    ]
    EXAMINE_STATUS_CHOICES = [
        ('0', '未审核'),
        ('1', '已审核'),
    ]

    id = models.AutoField(primary_key=True, verbose_name='ID')
    admin_id = models.IntegerField(null=True, blank=True, verbose_name='管理员ID')
    purchase_code = models.CharField(
        max_length=50,
        default='',
        verbose_name='单据编号'
    )
    purchase_time = models.IntegerField(
        default=0,
        verbose_name='单据日期'
    )
    business_type = models.CharField(
        max_length=1,
        choices=BUSINESS_TYPE_CHOICES,
        default='1',
        verbose_name='业务类型'
    )
    type = models.CharField(
        max_length=1,
        choices=TYPE_CHOICES,
        default='2',
        verbose_name='组件类型'
    )
    goods_id = models.IntegerField(
        default=0,
        verbose_name='商品ID'
    )
    goods_code = models.CharField(
        max_length=50,
        default='',
        verbose_name='商品编号'
    )
    goods_attr = models.IntegerField(
        null=True,
        blank=True,
        verbose_name='商品属性'
    )
    goods_unit = models.IntegerField(
        default=0,
        verbose_name='商品单位'
    )
    stores_id = models.IntegerField(
        default=0,
        verbose_name='仓库ID'
    )
    allow_stock = models.DecimalField(
        max_digits=15,
        decimal_places=4,
        default=0.0000,
        null=True,
        verbose_name='可用库存'
    )
    number = models.DecimalField(
        max_digits=15,
        decimal_places=4,
        default=0.0000,
        null=True,
        verbose_name='数量'
    )
    period = models.TextField(
        null=True,
        blank=True,
        verbose_name='序列号'
    )
    basic_number = models.DecimalField(
        max_digits=15,
        decimal_places=4,
        default=0.0000,
        null=True,
        verbose_name='基本数量'
    )
    unit_cost = models.FloatField(
        default=0,
        null=True,
        verbose_name='单位成本'
    )
    cost_money = models.FloatField(
        default=0,
        null=True,
        verbose_name='成本金额'
    )
    remark = models.CharField(
        max_length=255,
        null=True,
        blank=True,
        verbose_name='备注'
    )
    batch_id = models.IntegerField(
        null=True,
        blank=True,
        verbose_name='批次ID'
    )
    batch = models.CharField(
        max_length=255,
        null=True,
        blank=True,
        verbose_name='批次号'
    )
    manufacture = models.IntegerField(
        null=True,
        blank=True,
        verbose_name='生产日期'
    )
    guarantee = models.IntegerField(
        null=True,
        blank=True,
        verbose_name='保质期(天)'
    )
    validity = models.IntegerField(
        null=True,
        blank=True,
        verbose_name='过期时间'
    )
    preparation_id = models.IntegerField(
        null=True,
        blank=True,
        verbose_name='制单人'
    )
    operation_id = models.IntegerField(
        null=True,
        blank=True,
        verbose_name='操作人'
    )
    examine_id = models.IntegerField(
        null=True,
        blank=True,
        verbose_name='审核人'
    )
    examine_status = models.CharField(
        max_length=1,
        choices=EXAMINE_STATUS_CHOICES,
        default='0',
        verbose_name='审核状态'
    )
    examine_time = models.IntegerField(
        null=True,
        blank=True,
        verbose_name='审核时间'
    )
    print_num = models.IntegerField(
        default=0,
        null=True,
        verbose_name='打印次数'
    )
    createtime = models.IntegerField(
        null=True,
        blank=True,
        verbose_name='创建时间'
    )
    updatetime = models.IntegerField(
        null=True,
        blank=True,
        verbose_name='更新时间'
    )

    class Meta:
        db_table = 'fa_kuyou_assemble_info'
        verbose_name = '组装单详情'
        verbose_name_plural = '组装单详情'
        ordering = ['-purchase_time']

    def __str__(self):
        return f"{self.purchase_code}({self.get_type_display()})"

    def save(self, *args, **kwargs):
        """自动计算过期时间"""
        if self.manufacture and self.guarantee:
            self.validity = self.manufacture + self.guarantee * 86400
        now = int(time.time())
        self.createtime = now
        self.updatetime = now
        self.cost_money = float(self.basic_number) * float(self.unit_cost)
        super().save(*args, **kwargs)

    @property
    def total_cost(self):
        """计算总成本"""
        return float(self.unit_cost) * float(self.number)


# 组装模板
class FaKuyouAssembleTemp(models.Model):
    BUSINESS_TYPE_CHOICES = [
        ('1', '组装单'),
    ]

    EXAMINE_STATUS_CHOICES = [
        ('0', '未审核'),
        ('1', '已审核'),
    ]

    id = models.AutoField(primary_key=True)
    admin_id = models.IntegerField(null=True, blank=True)
    temp_name = models.CharField(
        max_length=255,
        default='',
        verbose_name='模板名称'
    )
    purchase_code = models.CharField(
        max_length=50,
        null=True,
        blank=True,
        verbose_name='单据编号'
    )
    purchase_time = models.IntegerField(
        null=True,
        blank=True,
        verbose_name='单据日期'
    )
    business_type = models.CharField(
        max_length=1,
        choices=BUSINESS_TYPE_CHOICES,
        null=True,
        blank=True,
        verbose_name='业务类型'
    )
    money = models.DecimalField(
        max_digits=15,
        decimal_places=4,
        null=True,
        blank=True,
        verbose_name='费用'
    )
    remark = models.CharField(
        max_length=255,
        null=True,
        blank=True,
        verbose_name='备注'
    )
    preparation_id = models.IntegerField(
        null=True,
        blank=True,
        verbose_name='制单人ID'
    )
    operation_id = models.IntegerField(
        null=True,
        blank=True,
        verbose_name='最后操作人ID'
    )
    examine_id = models.IntegerField(
        null=True,
        blank=True,
        verbose_name='审核人ID'
    )
    examine_status = models.CharField(
        max_length=1,
        choices=EXAMINE_STATUS_CHOICES,
        default='0',
        null=True,
        blank=True,
        verbose_name='审核状态'
    )
    examine_time = models.IntegerField(
        null=True,
        blank=True,
        verbose_name='审核时间'
    )
    print_num = models.IntegerField(
        null=True,
        blank=True,
        verbose_name='打印次数'
    )
    createtime = models.IntegerField(
        null=True,
        blank=True,
        verbose_name='创建时间',
        default=int(time.time())
    )
    updatetime = models.IntegerField(
        null=True,
        blank=True,
        verbose_name='更新时间',
        default=int(time.time())
    )

    class Meta:
        db_table = 'fa_kuyou_assemble_temp'
        verbose_name = '组装单模板'
        verbose_name_plural = '组装单模板'
        indexes = [
            models.Index(fields=['temp_name']),
            models.Index(fields=['purchase_code']),
            models.Index(fields=['examine_status']),
        ]

    def __str__(self):
        return f"组装单模板 {self.temp_name or self.id}"


# 组装模板详情
class FaKuyouAssembleInfoTemp(models.Model):
    BUSINESS_TYPE_CHOICES = [
        ('1', '组装单'),
    ]

    TYPE_CHOICES = [
        ('1', '组合件'),
        ('2', '子件'),
    ]

    EXAMINE_STATUS_CHOICES = [
        ('0', '未审核'),
        ('1', '已审核'),
    ]

    id = models.AutoField(primary_key=True)
    admin_id = models.IntegerField(null=True, blank=True)
    purchase_id = models.IntegerField(null=True, blank=True, verbose_name='关联模板ID')
    purchase_code = models.CharField(
        max_length=50,
        default='',
        verbose_name='单据编号'
    )
    purchase_time = models.IntegerField(
        default=0,
        verbose_name='单据日期'
    )
    business_type = models.CharField(
        max_length=1,
        choices=BUSINESS_TYPE_CHOICES,
        default='1',
        verbose_name='业务类型'
    )
    type = models.CharField(
        max_length=1,
        choices=TYPE_CHOICES,
        default='2',
        verbose_name='组件类型'
    )
    goods_id = models.IntegerField(
        default=0,
        verbose_name='商品ID'
    )
    goods_code = models.CharField(
        max_length=50,
        default='',
        verbose_name='商品编号'
    )
    goods_attr = models.IntegerField(
        null=True,
        blank=True,
        verbose_name='商品属性'
    )
    goods_unit = models.IntegerField(
        default=0,
        verbose_name='商品单位'
    )
    stores_id = models.IntegerField(
        default=0,
        verbose_name='仓库ID'
    )
    allow_stock = models.DecimalField(
        max_digits=15,
        decimal_places=4,
        default=0.0000,
        null=True,
        blank=True,
        verbose_name='可用库存'
    )
    number = models.DecimalField(
        max_digits=15,
        decimal_places=4,
        default=0.0000,
        null=True,
        blank=True,
        verbose_name='数量'
    )
    period = models.TextField(
        null=True,
        blank=True,
        verbose_name='序列号'
    )
    basic_number = models.DecimalField(
        max_digits=15,
        decimal_places=4,
        default=0.0000,
        null=True,
        blank=True,
        verbose_name='基本数量'
    )
    unit_cost = models.FloatField(
        default=0,
        null=True,
        blank=True,
        verbose_name='单位成本'
    )
    cost_money = models.FloatField(
        default=0,
        null=True,
        blank=True,
        verbose_name='成本'
    )
    remark = models.CharField(
        max_length=255,
        null=True,
        blank=True,
        verbose_name='备注'
    )
    batch_id = models.IntegerField(
        null=True,
        blank=True,
        verbose_name='批次ID'
    )
    batch = models.CharField(
        max_length=255,
        null=True,
        blank=True,
        verbose_name='批次'
    )
    manufacture = models.IntegerField(
        null=True,
        blank=True,
        verbose_name='生产日期'
    )
    guarantee = models.IntegerField(
        null=True,
        blank=True,
        verbose_name='保质期(天)'
    )
    validity = models.IntegerField(
        null=True,
        blank=True,
        verbose_name='过期时间'
    )
    preparation_id = models.IntegerField(
        null=True,
        blank=True,
        verbose_name='制单人ID'
    )
    operation_id = models.IntegerField(
        null=True,
        blank=True,
        verbose_name='最后操作人ID'
    )
    examine_id = models.IntegerField(
        null=True,
        blank=True,
        verbose_name='审核人ID'
    )
    examine_status = models.CharField(
        max_length=1,
        choices=EXAMINE_STATUS_CHOICES,
        default='0',
        null=True,
        blank=True,
        verbose_name='审核状态'
    )
    examine_time = models.IntegerField(
        null=True,
        blank=True,
        verbose_name='审核时间'
    )
    print_num = models.IntegerField(
        default=0,
        null=True,
        blank=True,
        verbose_name='打印次数'
    )
    createtime = models.IntegerField(
        null=True,
        blank=True,
        verbose_name='创建时间',
        default=int(time.time())
    )
    updatetime = models.IntegerField(
        null=True,
        blank=True,
        verbose_name='更新时间',
        default=int(time.time())
    )

    class Meta:
        db_table = 'fa_kuyou_assemble_info_temp'
        verbose_name = '组装单详情模板'
        verbose_name_plural = '组装单详情模板'
        indexes = [
            models.Index(fields=['purchase_id']),
            models.Index(fields=['purchase_code']),
            models.Index(fields=['goods_id']),
            models.Index(fields=['type']),
        ]

    def __str__(self):
        return f"模板详情 {self.id} - {self.get_type_display()} {self.goods_code}"


# 拆卸单
class FaKuyouSplit(models.Model):
    """拆卸单主表"""
    BUSINESS_TYPE_CHOICES = [
        ('1', '拆卸单'),
    ]
    EXAMINE_STATUS_CHOICES = [
        ('0', '未审核'),
        ('1', '已审核'),
    ]

    id = models.AutoField(primary_key=True, verbose_name='ID')
    admin_id = models.IntegerField(null=True, blank=True, verbose_name='管理员ID')
    purchase_code = models.CharField(
        max_length=50,
        null=True,
        blank=True,
        verbose_name='单据编号'
    )
    purchase_time = models.IntegerField(
        null=True,
        blank=True,
        verbose_name='单据日期'
    )
    business_type = models.CharField(
        max_length=1,
        choices=BUSINESS_TYPE_CHOICES,
        null=True,
        blank=True,
        verbose_name='业务类型'
    )
    money = models.DecimalField(
        max_digits=15,
        decimal_places=4,
        null=True,
        blank=True,
        verbose_name='费用'
    )
    remark = models.CharField(
        max_length=255,
        null=True,
        blank=True,
        verbose_name='备注'
    )
    preparation_id = models.IntegerField(
        null=True,
        blank=True,
        verbose_name='制单人ID'
    )
    operation_id = models.IntegerField(
        null=True,
        blank=True,
        verbose_name='操作人ID'
    )
    examine_id = models.IntegerField(
        null=True,
        blank=True,
        verbose_name='审核人ID'
    )
    examine_status = models.CharField(
        max_length=1,
        choices=EXAMINE_STATUS_CHOICES,
        default='0',
        verbose_name='审核状态'
    )
    examine_time = models.IntegerField(
        null=True,
        blank=True,
        verbose_name='审核时间'
    )
    print_num = models.IntegerField(
        null=True,
        blank=True,
        verbose_name='打印次数'
    )
    createtime = models.IntegerField(
        null=True,
        blank=True,
        verbose_name='创建时间'
    )
    updatetime = models.IntegerField(
        null=True,
        blank=True,
        verbose_name='更新时间'
    )

    class Meta:
        db_table = 'fa_kuyou_split'
        verbose_name = '拆卸单'
        verbose_name_plural = '拆卸单'
        ordering = ['-purchase_time']

    def __str__(self):
        return f"{self.purchase_code or '未编号单据'}"

    def save(self, *args, **kwargs):
        """自动设置单据日期"""
        if not self.purchase_time:
            from django.utils import timezone
            self.purchase_time = int(timezone.now().timestamp())
        super().save(*args, **kwargs)

    @property
    def status(self):
        """获取状态标签"""
        if self.examine_status == '1':
            return '已审核'
        return '未审核'


# 拆卸详情单
class FaKuyouSplitInfo(models.Model):
    """拆卸单明细表"""
    BUSINESS_TYPE_CHOICES = [
        ('1', '拆卸单'),
    ]
    TYPE_CHOICES = [
        ('1', '组合件'),
        ('2', '子件'),
    ]
    EXAMINE_STATUS_CHOICES = [
        ('0', '未审核'),
        ('1', '已审核'),
    ]


    admin_id = models.IntegerField(null=True, blank=True, verbose_name='管理员ID')
    purchase_code = models.CharField(
        max_length=50,
        default='',
        verbose_name='单据编号'
    )
    purchase_time = models.IntegerField(
        default=0,
        verbose_name='单据日期'
    )
    business_type = models.CharField(
        max_length=1,
        choices=BUSINESS_TYPE_CHOICES,
        default='1',
        verbose_name='业务类型'
    )
    type = models.CharField(
        max_length=1,
        choices=TYPE_CHOICES,
        default='2',
        verbose_name='组件类型'
    )
    goods_id = models.IntegerField(
        default=0,
        verbose_name='商品ID'
    )
    goods_code = models.CharField(
        max_length=50,
        default='',
        verbose_name='商品编号'
    )
    goods_attr = models.IntegerField(
        null=True,
        blank=True,
        verbose_name='商品属性'
    )
    goods_unit = models.IntegerField(
        default=0,
        verbose_name='商品单位'
    )
    stores_id = models.IntegerField(
        default=0,
        verbose_name='仓库ID'
    )
    allow_stock = models.DecimalField(
        max_digits=15,
        decimal_places=4,
        default=0.0000,
        null=True,
        verbose_name='可用库存'
    )
    number = models.DecimalField(
        max_digits=15,
        decimal_places=4,
        default=0.0000,
        null=True,
        verbose_name='数量'
    )
    period = models.TextField(
        null=True,
        blank=True,
        verbose_name='序列号'
    )
    basic_number = models.DecimalField(
        max_digits=15,
        decimal_places=4,
        default=0.0000,
        null=True,
        verbose_name='基本数量'
    )
    unit_cost = models.FloatField(
        default=0,
        null=True,
        verbose_name='单位成本'
    )
    cost_money = models.FloatField(
        default=0,
        null=True,
        verbose_name='成本金额'
    )
    remark = models.CharField(
        max_length=255,
        null=True,
        blank=True,
        verbose_name='备注'
    )
    batch_id = models.IntegerField(
        null=True,
        blank=True,
        verbose_name='批次ID'
    )
    batch = models.CharField(
        max_length=255,
        null=True,
        blank=True,
        verbose_name='批次号'
    )
    manufacture = models.IntegerField(
        null=True,
        blank=True,
        verbose_name='生产日期'
    )
    guarantee = models.IntegerField(
        null=True,
        blank=True,
        verbose_name='保质期(天)'
    )
    validity = models.IntegerField(
        null=True,
        blank=True,
        verbose_name='过期时间'
    )
    preparation_id = models.IntegerField(
        null=True,
        blank=True,
        verbose_name='制单人ID'
    )
    operation_id = models.IntegerField(
        null=True,
        blank=True,
        verbose_name='操作人ID'
    )
    examine_id = models.IntegerField(
        null=True,
        blank=True,
        verbose_name='审核人ID'
    )
    examine_status = models.CharField(
        max_length=1,
        choices=EXAMINE_STATUS_CHOICES,
        default='0',
        verbose_name='审核状态'
    )
    examine_time = models.IntegerField(
        null=True,
        blank=True,
        verbose_name='审核时间'
    )
    print_num = models.IntegerField(
        default=0,
        null=True,
        verbose_name='打印次数'
    )
    createtime = models.IntegerField(
        null=True,
        blank=True,
        verbose_name='创建时间'
    )
    updatetime = models.IntegerField(
        null=True,
        blank=True,
        verbose_name='更新时间'
    )

    class Meta:
        db_table = 'fa_kuyou_split_info'
        verbose_name = '拆卸单明细'
        verbose_name_plural = '拆卸单明细'
        ordering = ['-purchase_time']

    def __str__(self):
        return f"{self.purchase_code}-{self.goods_code}"

    def save(self, *args, **kwargs):
        """自动处理逻辑"""
        # 自动计算过期时间
        if self.manufacture and self.guarantee:
            self.validity = self.manufacture + self.guarantee * 86400

        # 自动计算成本金额
        if self.unit_cost is not None and self.number is not None:
            self.cost_money = float(self.unit_cost) * float(self.number)

        super().save(*args, **kwargs)

    @property
    def status_badge(self):
        """审核状态标签"""
        return 'success' if self.examine_status == '1' else 'warning'


# 拆卸模板
class FaKuyouSplitTemp(models.Model):
    """拆卸单模板主表"""
    BUSINESS_TYPE_CHOICES = [
        ('1', '拆卸单'),
    ]
    EXAMINE_STATUS_CHOICES = [
        ('0', '未审核'),
        ('1', '已审核'),
    ]

    id = models.AutoField(primary_key=True, verbose_name='ID')
    admin_id = models.IntegerField(null=True, blank=True, verbose_name='管理员ID')
    temp_name = models.CharField(
        max_length=255,
        default='',
        verbose_name='模板名称'
    )
    purchase_code = models.CharField(
        max_length=50,
        null=True,
        blank=True,
        verbose_name='单据编号'
    )
    purchase_time = models.IntegerField(
        null=True,
        blank=True,
        verbose_name='单据日期'
    )
    business_type = models.CharField(
        max_length=1,
        choices=BUSINESS_TYPE_CHOICES,
        null=True,
        blank=True,
        verbose_name='业务类型'
    )
    money = models.DecimalField(
        max_digits=15,
        decimal_places=4,
        null=True,
        blank=True,
        verbose_name='费用'
    )
    remark = models.CharField(
        max_length=255,
        null=True,
        blank=True,
        verbose_name='备注'
    )
    preparation_id = models.IntegerField(
        null=True,
        blank=True,
        verbose_name='制单人ID'
    )
    operation_id = models.IntegerField(
        null=True,
        blank=True,
        verbose_name='操作人ID'
    )
    examine_id = models.IntegerField(
        null=True,
        blank=True,
        verbose_name='审核人ID'
    )
    examine_status = models.CharField(
        max_length=1,
        choices=EXAMINE_STATUS_CHOICES,
        default='0',
        verbose_name='审核状态'
    )
    examine_time = models.IntegerField(
        null=True,
        blank=True,
        verbose_name='审核时间'
    )
    print_num = models.IntegerField(
        null=True,
        blank=True,
        verbose_name='打印次数'
    )
    createtime = models.IntegerField(
        null=True,
        blank=True,
        verbose_name='创建时间'
    )
    updatetime = models.IntegerField(
        null=True,
        blank=True,
        verbose_name='更新时间'
    )

    class Meta:
        db_table = 'fa_kuyou_split_temp'
        verbose_name = '拆卸单模板'
        verbose_name_plural = '拆卸单模板'
        ordering = ['-createtime']

    def __str__(self):
        return f"{self.temp_name}({self.id})"

    def save(self, *args, **kwargs):
        """自动处理模板特有逻辑"""
        from django.utils import timezone

        # 首次创建时设置时间戳
        if not self.createtime:
            self.createtime = int(timezone.now().timestamp())
        self.updatetime = int(timezone.now().timestamp())

        # 模板不允许审核状态
        if self.examine_status == '1':
            self.examine_status = '0'
            self.examine_id = None
            self.examine_time = None

        super().save(*args, **kwargs)


# 拆卸模板详情
class FaKuyouSplitInfoTemp(models.Model):
    """拆卸单明细模板表（用于暂存未提交数据）"""
    BUSINESS_TYPE_CHOICES = [
        ('1', '拆卸单'),
    ]
    TYPE_CHOICES = [
        ('1', '组合件'),
        ('2', '子件'),
    ]
    EXAMINE_STATUS_CHOICES = [
        ('0', '未审核'),
        ('1', '已审核'),
    ]

    id = models.AutoField(primary_key=True, verbose_name='ID')
    admin_id = models.IntegerField(null=True, blank=True, verbose_name='管理员ID')
    purchase_id = models.IntegerField(null=True, blank=True, verbose_name='关联单据ID')
    purchase_code = models.CharField(
        max_length=50,
        default='',
        verbose_name='单据编号'
    )
    purchase_time = models.IntegerField(
        default=0,
        verbose_name='单据日期'
    )
    business_type = models.CharField(
        max_length=1,
        choices=BUSINESS_TYPE_CHOICES,
        default='1',
        verbose_name='业务类型'
    )
    type = models.CharField(
        max_length=1,
        choices=TYPE_CHOICES,
        default='2',
        verbose_name='组件类型'
    )
    goods_id = models.IntegerField(
        default=0,
        verbose_name='商品ID'
    )
    goods_code = models.CharField(
        max_length=50,
        default='',
        verbose_name='商品编号'
    )
    goods_attr = models.IntegerField(
        null=True,
        blank=True,
        verbose_name='商品属性'
    )
    goods_unit = models.IntegerField(
        default=0,
        verbose_name='商品单位'
    )
    stores_id = models.IntegerField(
        default=0,
        verbose_name='仓库ID'
    )
    allow_stock = models.DecimalField(
        max_digits=15,
        decimal_places=4,
        default=0.0000,
        null=True,
        verbose_name='可用库存'
    )
    number = models.DecimalField(
        max_digits=15,
        decimal_places=4,
        default=0.0000,
        null=True,
        verbose_name='数量'
    )
    period = models.TextField(
        null=True,
        blank=True,
        verbose_name='序列号'
    )
    basic_number = models.DecimalField(
        max_digits=15,
        decimal_places=4,
        default=0.0000,
        null=True,
        verbose_name='基本数量'
    )
    unit_cost = models.FloatField(
        default=0,
        null=True,
        verbose_name='单位成本'
    )
    cost_money = models.FloatField(
        default=0,
        null=True,
        verbose_name='成本金额'
    )
    remark = models.CharField(
        max_length=255,
        null=True,
        blank=True,
        verbose_name='备注'
    )
    batch_id = models.IntegerField(
        null=True,
        blank=True,
        verbose_name='批次ID'
    )
    batch = models.CharField(
        max_length=255,
        null=True,
        blank=True,
        verbose_name='批次号'
    )
    manufacture = models.IntegerField(
        null=True,
        blank=True,
        verbose_name='生产日期'
    )
    guarantee = models.IntegerField(
        null=True,
        blank=True,
        verbose_name='保质期(天)'
    )
    validity = models.IntegerField(
        null=True,
        blank=True,
        verbose_name='过期时间'
    )
    preparation_id = models.IntegerField(
        null=True,
        blank=True,
        verbose_name='制单人ID'
    )
    operation_id = models.IntegerField(
        null=True,
        blank=True,
        verbose_name='操作人ID'
    )
    examine_id = models.IntegerField(
        null=True,
        blank=True,
        verbose_name='审核人ID'
    )
    examine_status = models.CharField(
        max_length=1,
        choices=EXAMINE_STATUS_CHOICES,
        default='0',
        verbose_name='审核状态'
    )
    examine_time = models.IntegerField(
        null=True,
        blank=True,
        verbose_name='审核时间'
    )
    print_num = models.IntegerField(
        default=0,
        null=True,
        verbose_name='打印次数'
    )
    createtime = models.IntegerField(
        null=True,
        blank=True,
        verbose_name='创建时间'
    )
    updatetime = models.IntegerField(
        null=True,
        blank=True,
        verbose_name='更新时间'
    )

    class Meta:
        db_table = 'fa_kuyou_split_info_temp'
        verbose_name = '拆卸单明细模板'
        verbose_name_plural = '拆卸单明细模板'
        ordering = ['-createtime']

    def __str__(self):
        return f"模板[{self.id}] - {self.goods_code}"

    def save(self, *args, **kwargs):
        """自动处理模板特有逻辑"""
        # 自动计算过期时间
        if self.manufacture and self.guarantee:
            self.validity = self.manufacture + self.guarantee * 86400

        # 自动计算成本金额（允许手动覆盖）
        if self.cost_money == 0 and self.unit_cost and self.number:
            self.cost_money = float(self.unit_cost) * float(self.number)

        super().save(*args, **kwargs)
